

#include "ChannelEncoder.h"

int ChannelEncoder::get_image(std::shared_ptr<bm_image> &out_img)
{
    while (true)
    {
        if (stop_flag_)
            break;

        std::unique_lock<std::mutex> lock(img_que_mtx_);
        if (img_que_.size() == 0)
        {
            return -1;
        }
        out_img = img_que_.front();
        img_que_.pop_front();
        return 0;
    }
    return 1;
}

void ChannelEncoder::push_image(std::shared_ptr<bm_image> bmimg)
{
    std::lock_guard<std::mutex> lock(img_que_mtx_);
    if (img_que_.size() >= max_que_size_)
    {
        img_que_.pop_front();
    }
    img_que_.push_back(bmimg);
}

void ChannelEncoder::dowork()
{
    unsigned int reconnet_times = 0;
    while (!stop_flag_)
    {
        std::cout << "encode reconnet stream times: " << reconnet_times++ << "  url:" + url_ << std::endl;
        int ret = encoder.openEnc(url_.c_str(), "h264_bm", 0, framerate, width,
                                  height, pix_fmt_, bitrate, dev_id_);

        if (ret < 0)
        {
            printf("open output media failed\n");
            usleep(1000 * 1000);
            continue;
        }
        std::cout << "encode start! " << std::endl;
        while (true)
        {
            if(stop_flag_)
            {
                break;
            }
            std::shared_ptr<bm_image> image;
            ret = get_image(image);
            if (ret < 0)
            {
                usleep(1000 * 100);
                continue;
            }
            AVFrame* frame = av_frame_alloc();
            frame->format = AV_PIX_FMT_NV12;
            frame->width = width;
            frame->height = height;
            bm_image* img = image.get();
            bm_image_to_avframe(handle_, img, frame);
            encoder.writeFrame(frame);
            av_frame_unref(frame);
        }
        // encoder.closeEnc();
        printf("encode finish! \n");
    }
}